from django.shortcuts import render, HttpResponse
from django.views.generic import View, ListView, TemplateView
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.hashers import make_password
from users.models import *
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required,permission_required


# 分页范围  防止越界的一个处理算法
def my_page(page_obj, paginator, page_nums=3):
    current_index = page_obj.number
    # 显示总页数
    # page_nums = 5
    # 限制显示范围 设置起始值
    start = current_index - page_nums // 2
    end = current_index + (page_nums // 2 + 1)
    # 如果小于第一页 就从第一页开始取
    if start <= 1:
        start = 1
    # 如果大约总页数  就取到最大页数
    if end >= paginator.num_pages:
        end = paginator.num_pages + 1
    # 如果取出页数后发现没有达到所需显示总页数（page_nums）
    current_pages_num = end - start
    # 当前end已经取到了最后
    if (end == paginator.num_pages + 1):
        # 所需显示总页数不够,就向前取
        start = start - (page_nums - current_pages_num)
    else:
        # 否则就向后取
        end = end + (page_nums - current_pages_num)
    # 如果小于第一页 就从第一页开始取
    if start <= 1:
        start = 1
    # # 如果大于总页数  就取到最大页数
    if end >= paginator.num_pages:
        end = paginator.num_pages + 1
    return range(start, end)


def faker_data(request):
    from faker import Faker
    for i in range(10):
        faker = Faker(locale='zh_CN')
        user = User()
        user.username = Faker().first_name()
        user.password = make_password(123456)
        user.email = faker.email()
        user.save()
        profile = Profile()
        profile.name_cn = faker.name()
        profile.wechat = faker.phone_number()
        profile.phone = profile.wechat
        profile.profile = user
        profile.save()
    return HttpResponse('添加测试数据')


# Create your views here.
# class UserListView(View):
#     def get(self,request):
#         user_list = User.objects.all()
#         return render(request,'user_list.html',locals())

class UserListView(ListView):
    template_name = 'user_list.html'
    model = User
    paginate_by = 7
    # 校验是否登录 装饰器调用写法
    # @method_decorator(login_required())
    # def get(self,request):
    #     return render(request,'user_list.html')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_range'] = self.page_range(context['page_obj'], context['paginator'])
        return context

    def page_range(self, page_obj, paginator):
        return my_page(page_obj, paginator, 5)


class UserAddView(TemplateView):

    # template_name = 'user_add.html'
    @method_decorator(permission_required('users.add_user'))
    def get(self, request):
        return render(request, 'user_add.html')

    def post(self, request):
        # print(request.POST)
        data = request.POST
        res = {'status': 0, 'msg': '添加用户成功'}
        try:
            user = User()
            user.username = data.get('username')
            user.password = make_password(data.get('password'))
            user.email = data.get('email')
            user.save()
            profile = Profile()
            profile.name_cn = data.get('name_cn')
            profile.wechat = data.get('wechat')
            profile.phone = data.get('phone')
            profile.profile = user
            profile.save()
        except Exception as e:
            print(e)
            res = {'status': 0, 'msg': '添加用户失败'}
        return JsonResponse(res)


class UserUpdateView(TemplateView):
    template_name = 'user_update.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['user_obj'] = User.objects.get(id=self.request.GET.get('id'))
        return context

    def post(self, request):
        data = request.POST
        res = {'status': 0, 'msg': '更新用户信息成功'}
        try:
            # 修改需要找到修改的对象操作
            user = User.objects.get(id=request.POST.get('id'))
            user.username = data.get('username')
            user.password = make_password(data.get('password'))
            user.email = data.get('email')
            user.save()
            # 一对一关系 找到需要修改的profile信息
            profile = user.profile
            profile.name_cn = data.get('name_cn')
            profile.wechat = data.get('wechat')
            profile.phone = data.get('phone')
            profile.profile = user
            profile.save()
        except Exception as e:
            print(e)
            res = {'status': 0, 'msg': '更新用户信息失败'}
        return JsonResponse(res)


class UserDeleteView(View):
    @method_decorator(permission_required('users.delete_user'))
    def get(self, request):
        res = {'status': 0, 'msg': '删除用户成功'}
        try:
            User.objects.get(id=request.GET.get('id')).delete()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '删除用户失败'}
        return JsonResponse(res)


class UserStatusView(View):
    def get(self, request):
        res = {'status': 0, 'msg': ''}
        try:
            user = User.objects.get(id=request.GET.get('id'))
            # 查询当前用户状态是什么
            # 如果用户当前为禁用状态
            if user.is_active == 0:
                # 设置启用
                user.is_active = 1
                res['msg'] = user.username + '启用成功'
            else:
                # 设置禁用
                user.is_active = 0
                res['msg'] = user.username + '禁用成功'
            user.save()
        except Exception as e:
            print(e)
            res['status'] = 1
            res['msg'] = '更新用户状态失败'
        return JsonResponse(res)


class GroupListView(ListView):
    template_name = 'group_list.html'
    model = Group
    paginate_by = 7

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        print(context)
        context['page_range'] = self.page_range(context['page_obj'], context['paginator'])
        return context

    def page_range(self, page_obj, paginator):
        return my_page(page_obj, paginator, 5)


class GroupAddView(ListView):
    template_name = 'group_add.html'
    model = User

    def post(self, request):
        # print(request.POST)
        # 添加用户组信息到用户组对象
        res = {'status': 0, 'msg': '添加用户组成功'}
        try:
            group = Group()
            group.name = request.POST.get('name')
            group.save()
            # 处理多对多的关系
            for i in request.POST.getlist('group_user'):
                # 反向添加用户和用户组关系
                group.user_set.add(User.objects.get(id=i))
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '添加用户组失败'}
        return JsonResponse(res)
        # return HttpResponse('测试接收数据')


class GroupUpdateView(ListView):
    template_name = 'group_update.html'
    model = User

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['group_obj'] = Group.objects.get(id=self.request.GET.get('id'))
        return context

    def post(self, request):
        # print(request.POST)
        res = {'status': 0, 'msg': '更新用户组信息成功'}
        # 修改数据,需要先查出对应的对象
        try:
            group = Group.objects.get(id=request.POST.get('id'))
            group.name = request.POST.get('name')
            group.save()
            # 处理多对多的关系
            # 修改多对多的数据信息 需要先移除掉之前的关联信息
            group.user_set.clear()
            for i in request.POST.getlist('group_user'):
                # 反向添加用户和用户组关系
                # 再重新添加关联信息
                group.user_set.add(User.objects.get(id=i))
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '更新用户组信息失败'}
        return JsonResponse(res)
        # return HttpResponse('用户组修改测试')


class GroupDeleteView(View):
    def get(self, request):
        res = {'status': 0, 'msg': '删除用户组成功'}
        group = Group.objects.get(id=request.GET.get('id'))
        if group.user_set.all():
            res = {'status': 1, 'msg': '用户组下有用户,请先清空用户关系'}
        else:
            try:
                # 删除用户组 会同时删除用户组和用户的关系 不会删除用户
                group.delete()
            except Exception as e:
                print(e)
                res = {'status': 1, 'msg': '删除用户组失败'}
        return JsonResponse(res)


class PermListView(ListView):
    template_name = 'perm_list.html'
    model = Permission

    # 重写返回数据信息
    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.exclude(name__regex="[A-Za-z]")
        return queryset


class UserSetPermView(ListView):
    template_name = 'user_set_perm.html'
    model = Permission

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['user_obj'] = User.objects.get(id=self.request.GET.get('id'))
        return context

    # 重写返回数据信息
    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.exclude(name__regex="[A-Za-z]")
        return queryset

    def post(self, request):
        # print(request.POST)
        res = {'status': 0, 'msg': '设置用户权限成功'}
        try:
            user = User.objects.get(id=request.POST.get('id'))
            user.user_permissions = request.POST.getlist('perm_list[]')
            user.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '设置用户权限失败'}
        return JsonResponse(res)
